import socket
import struct
import ConfigParser
import os
import sys

SYS_CONF_PATH = '/etc/ipgeotools/ipgeotools.cfg'
PROJECT_CONF_PATH = '../conf/ipgeotools.cfg'


def long_to_ip(int_ip):
    return socket.inet_ntoa(struct.pack('I', socket.htonl(int_ip)))


def ip_to_long(ip):
    return socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip)))[0])


def get_mysql_conf():
    conf = load_conf()
    host = get_or_default('mysql', 'host', 'localhost', conf)
    port = get_or_default('mysql', 'port', 3306, conf)
    username = get_or_default('mysql', 'username', None, conf)
    password = get_or_default('mysql', 'password', None, conf)
    db = get_or_default('mysql', 'db', 'ipgeotools', conf)
    table = get_or_default('mysql', 'table', 'ip_location', conf)
    return host, port, username, password, db, table


def get_or_default(section, option, default, conf):
    try:
        value = conf.get(section, option)
        if section == 'mysql' and option == 'port':
            return int(value)
        else:
            return value
    except ConfigParser.NoSectionError:
        return default
    except ConfigParser.NoOptionError:
        return default


def load_conf():
    if os.path.exists(SYS_CONF_PATH):
        conf_file = SYS_CONF_PATH
    elif os.path.exists(PROJECT_CONF_PATH):
        conf_file = PROJECT_CONF_PATH
    else:
        print 'ERROR: %s not found'
        sys.exit(-1)
    config = ConfigParser.ConfigParser()
    with open(conf_file, 'rw') as f:
        config.readfp(f)
    return config
